import "./index.scss";
import { Card, Form, Input, Button, message } from "antd";
import logo from "@/assets/logo.png";

import { useDispatch } from "react-redux";
import { fetchToken } from "@/store/modules/userStore";
import { useNavigate } from "react-router-dom";

const Login = () => {
  //电话校验
  const checkPhone = (rule, value) => {
    if (!value) {
      return Promise.reject("手机号不能为空");
    }
    const reg = /^1[3-9]\d{9}$/;
    if (reg.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject("手机号格式不正确");
  };
  //验证码校验
  const checkCode = (rule, value) => {
    if (!value) {
      return Promise.reject("验证码不能为空");
    }
    const reg = /^\d{6}$/;
    if (reg.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject("验证码格式不正确");
  };

  const dispatch = useDispatch();
  const navigate = useNavigate();
 
  const onFinish = async (values) => {
    console.log("提交表单", values);
    try {
      await dispatch(fetchToken(values));
      navigate("/");
      message.success("登录成功");
    } catch (err) {
      console.error("登录过程中发生错误:", err);
      message.error("登录失败，请检查网络或稍后重试");
    }
  };
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form onFinish={onFinish}>
          {/* <Form.Item
            name="mobile"
            rules={[{ required: true, validator: checkPhone }]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item> */}
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "请输入手机号" },
              {
                pattern: /^1[3-9]\d{9}$/,
                // pattern: /^(1[3-9]\d{9})|(12000000002)$/,
                message: "手机号码格式不对",
              },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[{ required: true, validator: checkCode }]}
          >
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
